package com.itheima.controller;


import com.itheima.common.R;
import com.itheima.dto.UserDto;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/frame")
public class FrameController {

    @Autowired
    private UserService userService;
    @Autowired
    private HttpServletRequest request;

    /**
     *
     * @param oldPassword
     * @param newPassword
     */
    //用户修改密码
    @PostMapping("/password")
    public void password(String oldPassword,String  newPassword ) {
        userService.password(oldPassword,newPassword);

    }

    /**
     *
     * @param username
     * @param password
     */
    //用户注册
    @PostMapping("/register")
    public void register(String username ,String password) {

        userService.register(username,password);
    }

    /**
     *
     * @return
     */
    //用户注销
    @PostMapping("/logout")
    public R  logout(){
        //清空用户session
        HttpSession session = request.getSession();
        session.invalidate();//销毁session
        //返回code=1
        return R.success("退出成功");
    }

    /**
     *
     * @param username
     * @param password
     * @return
     */
    //用户登录
    @PostMapping("/login")
    public String login(String username ,String password) {


        R r = userService.login(username,password);

        String token = null;
        if (r.getCode() == 1) {
            HttpSession session = request.getSession();
            session.setAttribute("user", (r.getData()));
            token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjI sImlhdCI6MTUzNTY4NjY0NSwiZXhwIjoxNTM2ODk2MjQ1fQ.bGV4qjcZcNYDBJj ihIsSbSEQyPa5SkVcUYuA0WfgDds";

        }

        return token;
    }

    //用户资料
    @PostMapping("/profile")
    public UserDto profile(){
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");


        return userService.profile((long) user.getId());

    }

}
